//
//  AEPersonViewController.m
//  AESOLAR_IOS
//
//  Created by Bin Tang on 2024/10/11.
//  Copyright © 2024 Mr.Wang. All rights reserved.
//

#import "AEPersonViewController.h"
#import "AE_Solar-Swift.h"
#import "AEPersonViewModel.h"
#import "AEPersonTopView.h" // 头部视图
#import "AEPersonInfoViewCell.h"
#import "LoginAccountInfo.h"
#import "AEShareInfoView.h" // 分享


//@import "StringExten"

@interface AEPersonViewController ()

@property (nonatomic, strong) AEPersonViewModel *viewModel;

@property (nonatomic, strong) AEPersonTopView *topView;

@property (nonatomic, strong) UIView *footerView;

@property (nonatomic, strong) AEShareInfoView *shareView;

@end

@implementation AEPersonViewController

- (void)dealloc {
    debugMethod();
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    NSString *title = @"江苏新源";
//    [title localized];
//    StringExten *tm = [StringExten new];
//    [tm printSwiftWithStr:@"dd"];
//    PersonalViewController *vc = [[PersonalViewController alloc] init];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}

- (void)initWithVar {
    [super initWithVar];
    
    [self fromServerRequestData];
    
    // 用户信息刷新通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userInfoRefreshNoti:) name:@"userInfoRefresh" object:nil];
}

- (void)initWithViewModel {
    _viewModel = [AEPersonViewModel new];
}

- (void)initWithNavBar {
    [super initWithNavBar];
}

- (void)initWithSubView {
    [super initWithSubView];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#F6F8F8"];
//    self.baseTableView.hidden = YES;
    self.baseTableView.backgroundColor = [UIColor colorWithHexString:@"#F6F8F8"];
    
    [self initWithTopView];
    
    self.baseTableView.top = self.topView.bottom + 8;
    self.baseTableView.height = kScreenH - TABBAR_HEIGHT - self.topView.bottom - 8;
    [self.baseTableView registerClass:[AEPersonInfoViewCell class] forCellReuseIdentifier:[AEPersonInfoViewCell className]];
    
    [self initWithShareView];
}

- (void)initWithFooterView {
    [super initWithFooterView];
    
//    CGRect frame = CGRectMake(0, 0, kScreenW, 90);
    CGRect frame = CGRectMake(0, 0, kScreenW, 150);
    _footerView = [[UIView alloc] initWithFrame:frame];
    self.baseTableView.tableFooterView = _footerView;
    
    NSString *title = [AEStringExten localizedValueWithKey:@"退出登录"];
    CGRect bframe = CGRectMake(20, 10, kScreenW - 40, 44);
    UIButton *btnLogout = [UIButton createWithButton:self.footerView frame:bframe font:[UIFont systemFontOfSize:18 weight:UIFontWeightBold] target:self action:@selector(actionWithLogout:) propertiesBlock:^(UIButton * _Nonnull button) {
        button.backgroundColor = [UIColor colorWithHexString:@"#F4151D"];
        button.layer.cornerRadius = 8;
        button.layer.masksToBounds = YES;
        [button setTitle:title forState:UIControlStateNormal];
        [button setTitleColor:kWhiteColor forState:UIControlStateNormal];
    }];
    
    
    title = [AEStringExten localizedValueWithKey:@"删除账号"];
    bframe = CGRectMake(20, self.footerView.height - 44 - 40, kScreenW - 40, 44);
    UIButton *btnDelAccount = [UIButton createWithButton:self.footerView frame:bframe font:[UIFont systemFontOfSize:18 weight:UIFontWeightBold] target:self action:@selector(actionWithDelAccount:) propertiesBlock:^(UIButton * _Nonnull button) {
        button.backgroundColor = [UIColor colorWithHexString:@"#F4151D"];
        button.layer.cornerRadius = 8;
        button.layer.masksToBounds = YES;
        [button setTitle:title forState:UIControlStateNormal];
        [button setTitleColor:kWhiteColor forState:UIControlStateNormal];
    }];
    
    _footerView.hidden = YES;
}

- (void)initWithTopView {
    if (!_topView) {
        CGRect frame = CGRectMake(0, 0, kScreenW, 314);
        _topView = [[AEPersonTopView alloc] initWithFrame:frame];
        [self.view addSubview:_topView];
        
        // 点击分享领积分
        @weakify(self);
        self.topView.touchSharePointsBlock = ^{
            @strongify(self);
            [self actionWithSharePoints];
        };
        
        // 反馈
        self.topView.touchFeedbackBlock = ^{
            @strongify(self);
            [self actionWithFeedback];
        };
        
        // 设置
        self.topView.touchSettingBlock = ^{
            @strongify(self);
            [self actionWithSetting];
        };
    }
    [self.topView updateWithViewData:self.viewModel];
}

/// 分享
- (void)initWithShareView {
    if (!_shareView) {
        float height = 226 + IPHONEX_BOTTOM_SPACE;
        CGRect frame = CGRectMake(0, kScreenH - height , kScreenW, height);
        _shareView = [[AEShareInfoView alloc] initWithFrame:frame];
    }
}

/// 点击分享领积分
- (void)actionWithSharePoints {
//    [SVProgressHUD showInfoWithStatus:@"点击分享领积分"];
    @weakify(self);
    [self.viewModel requestWithSysConfig:^(EDSRespondDataEntity * _Nonnull respond) {
        @strongify(self);
        [self showShareVC];
    }];
}

/// 显示分享弹窗
- (void)showShareVC {
    /*
    @weakify(self);
    [_shareView showWithTitle:@"立即分享给好友" data:nil completion:^(id  _Nonnull data) {
        @strongify(self);
        NSInteger tag = [data integerValue];
        if (tag == 100) { // 微信
            [EDSUtility shareWithTitle:@"分享" desc:@"这个挺好的" shareUrl:@"https://www.baidu.com" shareType:1];
        } else if (tag == 101) { // 朋友圈
            [EDSUtility shareWithTitle:@"分享" desc:@"这个挺好的" shareUrl:@"https://www.baidu.com" shareType:2];
        }
    } failed:^{
        @strongify(self);
        [self.shareView hide];
    }];*/
    
    
    NSURL *url = [NSURL URLWithString:self.viewModel.configModel.apple_store];
    UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:@[url] applicationActivities:nil];
    @weakify(self);
    activityVC.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
        @strongify(self);
        if (completed) {
//            debugLog(@"完成");
            [self requestWithShareSuccess];
        } else {
//            debugLog(@"未完成");
        }
    };
    
    [self presentViewController:activityVC animated:YES completion:^{
//        debugLog(@"完成了");
    }];
     
}

/// 分享成功后调用
- (void)requestWithShareSuccess {
//    @weakify(self);
    [self.viewModel requestWithShareSuccess:^(EDSRespondDataEntity * _Nonnull respond) {
//        @strongify(self);
        if (respond.code == EDS_NETWORK_SUCCESS) {
            // 发送通知
            [[NSNotificationCenter defaultCenter] postNotificationName:@"userInfoRefresh" object:nil];
        } else {
            [SVProgressHUD showInfoWithStatus:respond.msg];
        }
    }];
}

/// 用户信息刷新通知
/// - Parameter noti: noti description
- (void)userInfoRefreshNoti:(NSNotification *)noti {
    [self fromServerRequestData];
}

/// 设置
- (void)actionWithSetting {
    SettingViewController *settingVC = [[SettingViewController alloc] init];
    [TYZJumpVCManager pushBaseVC:self pushVC:settingVC];
}

/// 反馈
- (void)actionWithFeedback {
    ServiceViewController *vc = [[ServiceViewController alloc] init];
    [TYZJumpVCManager pushBaseVC:self pushVC:vc];
}

/// 删除账号
/// - Parameter sender: sender description
- (void)actionWithDelAccount:(id)sender {
//    AppCache.sharedCache objectForKey:
    NSString *email = [AEUserCommonInfo getLoginEmail];
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:[AEStringExten localizedValueWithKey:@"系统提示"] message:[AEStringExten localizedValueWithKey:@"确定要删除吗？"] preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:[AEStringExten localizedValueWithKey:@"取消"] style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    @weakify(self);
    UIAlertAction *videoAction = [UIAlertAction actionWithTitle:[AEStringExten localizedValueWithKey:@"确定"] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        @strongify(self);
        [LoginAccountInfo saveAccount:email completion:^{
            [self requestWithLogout];
        }];
    }];
    
    [alertController addAction:cancelAction];
    [alertController addAction:videoAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

/// 退出登录
/// - Parameter sender: sender description
- (void)actionWithLogout:(id)sender {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:[AEStringExten localizedValueWithKey:@"系统提示"] message:[AEStringExten localizedValueWithKey:@"确定要退出登录吗？"] preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:[AEStringExten localizedValueWithKey:@"取消"] style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    @weakify(self);
    UIAlertAction *videoAction = [UIAlertAction actionWithTitle:[AEStringExten localizedValueWithKey:@"确定"] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        @strongify(self);
        [self requestWithLogout];
    }];
    
    [alertController addAction:cancelAction];
    [alertController addAction:videoAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

/// 退出登录
- (void)requestWithLogout {
//    @weakify(self);
    [self.viewModel requestWithLogout:^(EDSRespondDataEntity * _Nonnull respond) {
//        @strongify(self);
        if (respond.code == EDS_NETWORK_SUCCESS) {
            [AEUserCommonInfo jumpLoginVC]; // 跳转到登录页面
        } else {
            [SVProgressHUD showInfoWithStatus:@"退出登录失败，请稍后再试！"];
        }
    }];
}

- (void)fromServerRequestData {
    @weakify(self);
    [self.viewModel requestWithUserInfo:^(EDSRespondDataEntity * _Nonnull respond) {
        @strongify(self);
        [self.baseTableView reloadData];
        self.footerView.hidden = NO;
        [self initWithTopView];
    }];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.viewModel.dataList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    TYZCommonCellModel *model = [self.viewModel.dataList objectOrNilAtIndex:indexPath.row];
    return model.cellHeight;
//    return kAEPersonInfoViewCellHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TYZCommonCellModel *model = [self.viewModel.dataList objectOrNilAtIndex:indexPath.row];
    AEPersonInfoViewCell *cell = [AEPersonInfoViewCell cellForTableView:tableView indexPath:indexPath];
    [cell updateCellData:model];
    return cell;
}

@end
